import { BrowserWindow, BrowserWindowConstructorOptions, shell } from "electron";
import { join } from "path";
import { is } from "@electron-toolkit/utils";



export default class SubWindow {
    public static createWindow(config:BrowserWindowConstructorOptions & {url?:string} = {}): BrowserWindow {
        // Create the browser window.
        const subWin = new BrowserWindow(config)

        subWin.on('ready-to-show', () => {
            subWin.show()
        })

        subWin.webContents.setWindowOpenHandler((details) => {
            shell.openExternal(details.url)
            return { action: 'deny' }
        })

        // HMR for renderer base on electron-vite cli.
        // Load the remote URL for development or the local html file for production.
        if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
            subWin.loadURL(process.env['ELECTRON_RENDERER_URL'] + config.url)
        } else {
            subWin.loadFile(join(__dirname, '../renderer',  config.url||''))
        }

        const winID = subWin.webContents.id
        // map存储窗口ID
        global.winObj.winMap.set('subs', winID)
        // 全局存储窗口对象
        global['winstates-' + winID] = subWin
    
        subWin.on('closed', async function () {
          // 窗口关闭，需删除对应的全局窗口
          delete global['winstates-' + winID]
          global.winObj.winMap.delete('subs')
        })
        return subWin;
    }
}